package engine.parsers.impl;

import java.util.List;


import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndEnclosure;
import com.sun.syndication.feed.synd.SyndEntry;

import engine.content.IContent;
import engine.content.RSSContent;
import engine.parsers.IParser;
import engine.services.IContentService;



public class ImageFromRSSParser  implements IParser{

	
	@SuppressWarnings("unchecked")
	@Override
	public IContent parse(IContent content, IContentService contentService) throws Exception {
		RSSContent rss = (RSSContent)content;
		SyndEntry entry = rss.getFeedIterator().next();
		
		String imgStr = null;
		
		// first look for media enclosure, 
		// if not we will look for the URL from the description
		List<SyndEnclosure> enclosureList = entry.getEnclosures();
		if (enclosureList != null && enclosureList.size() > 0) {
			SyndEnclosure e = enclosureList.get(0);
			imgStr = e.getUrl().toString();
		} else {
			SyndContent description = entry.getDescription();
			imgStr = description.getValue();
			int startImgStr = imgStr.indexOf("src") + 5;
			int endImgStr = imgStr.indexOf("\"", startImgStr); 
			imgStr = imgStr.substring(startImgStr, endImgStr);			
		}

		return contentService.getResponse(imgStr);
	}
}